package com.edu.Filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String action=request.getParameter("action");//action
        if("adminLogin".equals(action)||"/CodeServlet.do".equals(requestURI)){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            Object nowuser = request.getSession().getAttribute("nowUser");
            if (nowuser != null) {
                // 如果 session 中有 admin 对象，继续执行过滤器链
                filterChain.doFilter(request, servletResponse);
            } else {
                response.sendRedirect("/login.jsp");
            }
        }

    }

    @Override
    public void destroy() {

    }
}
